import React, { useEffect, useRef, createRef, useState } from "react";

import { App } from "./system/App";
import { Config } from "./game/Config";
import useGame from "@/components/pages/game/ball/store/useGame";
import { Avatar, Button, Modal, Toast } from "antd-mobile";
import requewt from "@/utils/requewt";
import callFeedback from "@/components/common/modalFeedback";
import { API, AVATAR_URL, BASE_PATH } from "@/config";
import { useCountDown } from 'ahooks'
import {
  appNavigate,
  appTypeCheck,
  checkENV2,
  isValidArr,
  navigateTo,
  triggerAppShare,
  triggerShare,
  wxappNavigate
} from "@/utils";
import GameResult from "@/components/common/modalFeedback/game.result";
import { useRouter } from "next/router";
import classnames from "classnames";

let timer;

export default function ({pos}) {
  const router = useRouter();
  const [shaking, setShaking] = useState(false)
  const increase = useGame(state => state.increase);
  const start = useGame(state => state.start);
  const end = useGame(state => state.end);
  const points = useGame(state => state.points);
  const target = useGame(state => state.target);
  const duration = useGame(state => state.duration);
  const updateTimer = useGame(state => state.updateTimer);
  const phase = useGame(state => state.phase);
  const [targetTime, setTargetTime] = useState()
  const [resp, setResp] = useState(null)
  const [countDown] = useCountDown({
    targetDate: targetTime,
    onEnd() {
      console.log('endddd')
    }
  })
  // console.log(countDown, 'countDowncountDowncountDown')
  const au = useRef();

  useEffect(() => {
    (async () => {
      // App.run(Config, handler);

      // const resp = await requewt(API.user.userinfo);
      // if (resp?.error_code === 0 && resp?.msg === `ok`) setUser(resp?.data);
      // App.run(Config, handler);


    })()

    return () => {
      Modal?.clear();
      Toast.clear();
    }
  }, [])

  useEffect(() => {
    window.countDown = countDown;
    window.phase = phase;
    // console.log(phase, countDown);
    if (phase === "ended") {
      if (countDown === 0) {
        // end()
        // clearInterval(timer)
        // timer = 0;
        handler.finish()
      }
    }
  }, [countDown, phase])

  useEffect(() => {
    if (!points) return
    setShaking(true);
    setTimeout(() => setShaking(false), 1000);
  }, [points])

  const handler = {
    phasing: () => {
      console.log(this)
    },
    update: score => {
      console.log(`score`, score);
      // au.current.play()
      switch (score) {
        case 1:
        case 2:
        case 3:
        case 4:
          setTargetTime(Date.now() + 12000)
          break
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
          setTargetTime(Date.now() + 10000)
          break
        case 14:
        case 18:
        case 22:
          setTargetTime(Date.now() + 9000)
          break
        default:
          setTargetTime(Date.now() + 4000)
      }
      increase(score);
    },
    finish: async () => {
      const options = {
        method: `POST`,
        headers: {"Content-Type": "multipart/form-data"},
        body: {"score": points},
      }
      const resp = await requewt(API.game.finish, options);
      // alert(resp.error_code);
      if (resp?.error_code === 999) {
        window.location.href = `/basketball716/game`;
        return;
      }
      const isWin = resp.data?.status;
      const result = isWin ? `win` : `lose`;
      const title = isWin ? `恭喜你完成满电挑战` : `挑战失败`;
      const content = isWin ? <>您的成绩为：{points}分</> : <>
        你的分数为：{points}分 <br />
        再试一次吧
      </>;

      const actions = isWin ? [<Button onClick={e => navigateTo(`/wheel`)}
                                       className={`act-btn act-btn-bevel`}>去抽奖</Button>] : <></>

      const m = callFeedback({
        closeOnAction: false,
        closeOnMaskClick: false,
        bodyClassName: `game-feedback ${result}`,
        content: <GameResult title={title}
                             content={content}
                             actions={actions}
        />,
        hideClose: true,
        actions: [
          <Button onClick={e => {
            navigateTo(`/landing`)
            // setTimeout(() => {
            //   location.reload()
            // }, 10);
          }} className={`act-btn act-btn-bevel`}>返回首页</Button>,
          <Button onClick={e => {
            // m.close()
            // handler.start()
            // window.location.href = `basketball716/game`
            window.location.href = `/basketball716/game`
            // router.reload()
          }} className={`act-btn act-btn-bevel`}>继续游戏</Button>
        ]
      })
    },
    play: async () => {
      Toast.show({icon: 'loading', content: '加载中', duration: 0, maskClickable: false})
      const resp = await requewt(API.game.start);
      // alert(resp?.error_code);
      Toast.clear()
      if (resp?.error_code == 1010) {
        console.log("需要去分享")
        const c = callFeedback({
          title: <div dangerouslySetInnerHTML={{__html: resp?.msg || `失败`}} />,
          actions: [
            <Button key={`confirm`} onClick={async e => {
              const env = await checkENV2();
              if (env === `app`) await triggerAppShare()
              else if (env === `mini`) {
                Toast.show({content: `点击右上角「...」进行分享`})
              } else {
                Toast.show({content: `请在APP或小程序内打开`})
              }

              const resp = await requewt(API.user.share);
              if (resp?.error_code !== 0) return;
              // Toast.show({content: `分享成功`});
              // c.close();
            }} size="small" className="act-btn act-btn-primary">分享</Button>,
          ],
          closeOnAction: true,
          closeOnMaskClick: false,
        })
        return
      }
      console.log(resp);
      if (resp?.msg == "ok") {
        start();
        // console.log(App)
        App.scenes.scene.hero.heroInitJump()
        setTargetTime(Date.now() + 12000)
        au.current.play();
      }else{
        Toast.show({content: `请求游戏失败`})
      }
    },
    start: async () => {
      //  else {
        
        
        // timer = setInterval(() => {
        //   updateTimer()
        // }, 1000)
        setTimeout(() => {
          
          App.run(Config,handler)
        }, 200)
    },
    sendEnd: ()=> {
      // console.log(window.phase, phase);
      if (window.phase === "playing") {
        au.current.pause();
        end();
      }
    }
  }
  useEffect(() => {
    console.log(App,'app')
    handler.start()
  }, [])
  return (
    <>
      {
        phase === 'ready' &&
        <div className="starter">
          <div className="inner">
            <img className="img-fluid"
                 onClick={handler.play}
                 src={`${BASE_PATH}/img/game/game-guide.jpg`}
                 alt="" />

          </div>
        </div>
      }

      <div className={classnames("", {"animate__animated animate__faster  animate__shakeY": shaking})}>
        {
          <div id="game-wrapper">
            <div id="game-render" />
            <div id={`game`} />
          </div>
        }
      </div>


      <div className="board">
        <div className="timer-wrapper">
          <div className="val">
            时间：{Math.round(countDown / 1000)} 秒
          </div>
        </div>

        <div className="score-wrapper">
          <div className="val">
            分数：{points} 分
          </div>
        </div>
      </div>

      <div className="dashboard">
        <div className="inner">
          <img src={`${BASE_PATH}/img/game/game-car.png`} alt="" className="car" />

          <div className="battery-wrapper">
            <div className={classnames(`battery-bar`)}
                 style={{maxWidth: `100%`, width: `${(points / target * 100).toFixed(2)}%`}}>
              {
                points >= target &&
                <>
                  <img src={`${BASE_PATH}/img/game/game-battery-light.png`} alt="" className="light" />
                  <div className="power" />
                </>
              }
            </div>
          </div>
        </div>
        <audio controls loop src="https://yinli-qixi-run.varwey.com/2023/july/basketball716/bg_sm.mp3" ref={au} />
      </div>

    </>
  )
}